<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles">
              <el-table-column label="序号" type="index" width="120" :index="fn" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" type="success" @click="hAssign(scope.row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[1, 2, 3]"
                :page-size="pageParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 编辑添加弹出层 -->
    <el-dialog
      :title="isEdit ? '编辑角色' : '新增角色'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="close"
    >
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="showDialog = false">取消</el-button>
          <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 分配权限的弹层 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showDialogAssign"
    >
      <assign-permission v-if="showDialogAssign" :role-id="roleId" @close="showDialogAssign=false" />
    </el-dialog>
  </div>
</template>

<script>
import { getRules, doDelRules, addRole, updateRole } from '@/api/settings.js'
import assignPermission from './assignPermission'
export default {
  components: {
    assignPermission
  },
  data() {
    return {
      roles: [],
      pageParams: {
        page: 1,
        pagesize: 2
      },
      total: null,
      showDialog: false,
      showDialogAssign: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      isEdit: false,
      roleId: ''
    }
  },
  computed: {
    // 表格中最大的页码
    maxNum() {
      return Math.ceil(this.total / this.pageParams.pagesize)
    },
    // 最后一页是不是满的
    isLastPageFulled: function() {
      return this.total % this.pageParams.pagesize === 0
    }
  },
  created() {
    this.doGetRules()
  },
  methods: {
    async doAdd() {
      try {
        const res = await addRole(this.roleForm)
        console.log(res)
        if (this.isLastPageFulled) {
          this.pageParams.page = this.maxNum + 1
          this.total++
        } else {
          // 想查看最新添加的数据，要跳到最大页码
          this.pageParams.page = this.maxNum
        }
        this.doGetRules()
        this.$message.success('添加成功')
        this.showDialog = false
      } catch (err) {
        this.$message.error('添加失败')
        console.log(err)
      }
    },
    // 获取员工信息
    async doGetRules() {
      const res = await getRules(this.pageParams)
      console.log(res)
      this.total = res.data.total
      this.roles = res.data.rows
    },
    handleSizeChange(size) {
      this.pageParams.pagesize = size
      this.doGetRules()
    },
    handleCurrentChange(page) {
      this.pageParams.page = page
      this.doGetRules()
    },
    // 根据id删除员工
    async doDel(id) {
      await doDelRules(id)
      if (this.roles.length === 1) {
        if (this.pageParams.page > 1) {
          this.pageParams.page--
        }
      }
      this.doGetRules()
    },
    // 点击删除
    hDel(id) {
      this.$confirm('你确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch(() => {
        // 用户取消退出
      })
    },
    fn(index) {
      const { pageParams } = this
      return (pageParams.page - 1) * pageParams.pagesize + index + 1
    },
    async doEdit() {
      try {
        const res = await updateRole(this.roleForm)
        console.log(res)

        this.loadRoles()
        this.$message.success('编辑成功')
        this.showDialog = false
      } catch (err) {
        this.$message.error('编辑失败')
        console.log(err)
      }
    },
    // 用户点击了保存
    hSubmit() {
      console.log('提交')
      // 手动兜底校验
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    close() {
      this.roleForm = {
        name: '',
        description: ''
      }
      this.showDialog = false
    },
    hEdit(row) {
      // 1. 把当前的数据直接给表单
      this.roleForm = { ...row }

      // 2. 显示弹层
      this.showDialog = true
    },
    hAdd() {
      this.isEdit = false
      // 2. 显示弹层
      this.showDialog = true
    },
    hAssign(id) {
      this.showDialogAssign = true
      this.roleId = id
    }
  }

}
</script>
